package net.oschina.simpleplus.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.google.protobuf.ByteString;
import com.google.protobuf.GeneratedMessageV3;

import net.oschina.simpleplus.entity.Protobuf;

public class ConvertUtil {

	private ConvertUtil() {
	}
	
	private static final Convertor<byte[], ByteString> c1 = new Convertor<byte[], ByteString>() {
		
		@Override
		public ByteString covert(byte[] m) {
			return ByteString.copyFrom(m);
		}
	};

	private static final Convertor<ByteString, byte[]> c2 = new Convertor<ByteString, byte[]>() {
		
		@Override
		public byte[] covert(ByteString m) {
			return m.toByteArray();
		}
	};
	
	private static final Convertor<Protobuf<GeneratedMessageV3>, GeneratedMessageV3> c3 = new Convertor<Protobuf<GeneratedMessageV3>, GeneratedMessageV3>() {
		
		@Override
		public GeneratedMessageV3 covert(Protobuf<GeneratedMessageV3> m) {
			return m.build();
		}
	};
	
	public static List<ByteString> covert2ByteString(List<byte[]> ms){
		return covert(ms, c1);
	}
	
	
	public static List<byte[]> covert2bytes(List<ByteString> ms){
		return covert(ms, c2);
	}
	
	
	public static List covert2Protos(List<? extends Protobuf> ms){
		return covert(ms, c3);
	}
	

	public static <M,N> List<N> covert(List<M> ms, Convertor<M, N> c) {
		if(ms == null || ms.isEmpty()){
			return Collections.EMPTY_LIST;
		}
		List<N> ns = new ArrayList<N>(ms.size());
		for(M m : ms){
			ns.add(c.covert(m));
		}
		return ns;
	}
}
